package com.gamota.mobi.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;


import com.gamota.mobi.db.DatabaseHelper;
import com.gamota.mobi.event.Event.CheckUserBirthdayFailed;
import com.gamota.mobi.event.Event.CheckUserBirthdaySucceed;
import com.gamota.mobi.event.Event.ConfirmUserBirthdayFailed;
import com.gamota.mobi.event.Event.ConfirmUserBirthdaySucceed;
import com.gamota.mobi.model.UserInfo;
import com.gamota.mobi.util.CommonUtils;
import com.gamota.mobi.util.Constants;
import com.gamota.mobi.util.JsonUtil;
import com.gamota.mobi.util.Utils;

import de.greenrobot.event.EventBus;

public class HttpHelper {

	public static final String TAG = "HttpHelper";

	public static UserInfo getUserInfo(String access_token) {
		String requestUrl = Constants.USER_INFO_ENDPOINT + access_token;
//		Log.e(TAG, requestUrl);
		HttpGet httpGet = new HttpGet(requestUrl);
		HttpClient client = HttpUtils.getNewHttpClient();
		HttpResponse response;
		UserInfo  user=null;
		try {
			response = client.execute(httpGet);
//			Log.e("connectstatus", "connect : " + response.getStatusLine().getStatusCode());
			String s;
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				s = CommonUtils.inputStreamToString(inputStream);
//				Log.e("GetUserInfo-response", s);
				client.getConnectionManager().shutdown();
				client = null;
				try{
				JSONObject json=new JSONObject(s);
            		boolean status = json.getBoolean("status");
            		if(status){
            			JSONObject obj = json.getJSONObject("data");
            			user = new UserInfo();
            			user.setAvatarUr(obj.getString("avatar"));
            			user.setBirthday(obj.getString("birthday"));
            			user.setFullName(obj.getString("fullname"));
            			user.setUserName(obj.getString("username"));
            			user.setGender(obj.getString("gender"));
            			user.setGreenTym(obj.getInt("blue_tym"));
            			user.setPurpleTym(obj.getInt("purple_tym"));
            			user.setYellowTym(obj.getInt("yellow_tym"));
            		} 
				}catch(Exception ex)
				{
					ex.printStackTrace();
				}
			}
			client = null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		}
		return user;
	}

	public static String getShop(String type,String vendor,int start,int limit,String order,String access_token) {
		String lang = Locale.getDefault().getLanguage();
		if (!lang.equalsIgnoreCase("vi")) {
			lang = "en";
		}
		String result = "";
		String url_request = API.SHOP_GET_URL  + API.ACCESS_TOKEN
				+ "=" + access_token + "&lang="+lang;
//		Log.e(TAG, url_request);
		HttpPost httpPost = new HttpPost(url_request);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("store" , "android"));
		if(!TextUtils.isEmpty(type))
		{
			nameValuePairs.add(new BasicNameValuePair("type", type));
		}
		if(!TextUtils.isEmpty(vendor))
		{
			nameValuePairs.add(new BasicNameValuePair("vendor", vendor));
		}
		if(!TextUtils.isEmpty(order))
		{
			nameValuePairs.add(new BasicNameValuePair("order", order));
		}
		if(start!=0)
		{
			nameValuePairs.add(new BasicNameValuePair("start", String.valueOf(start)));
		}
		if(limit!=0)
		{
			nameValuePairs.add(new BasicNameValuePair("limit", String.valueOf(limit)));
		}
		HttpClient client = HttpUtils.getNewHttpClient();
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = client.execute(httpPost);
//			Log.e("HttpHelperGetShop", response.getStatusLine().getStatusCode() + "");
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				result = CommonUtils.inputStreamToString(inputStream);
				client = null;
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		}
//		Log.e("GetShop-Res", result);
		return result;
	}
	public static String exchangeGift(String giftId,String access_token) {
		String lang = Locale.getDefault().getLanguage();
		if (!lang.equalsIgnoreCase("vi")) {
			lang = "en";
		}
		String result = "";
		String url_request = API.USER_BUY_URL  + API.ACCESS_TOKEN
				+ "=" + access_token + "&lang="+lang;
//		Log.e(TAG, url_request);
		HttpPost httpPost = new HttpPost(url_request);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("id" , giftId));
		HttpClient client = HttpUtils.getNewHttpClient();
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = client.execute(httpPost);
//			Log.e("HttpHelperGetShop", response.getStatusLine().getStatusCode() + "");
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				result = CommonUtils.inputStreamToString(inputStream);
				client = null;
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		}
//		Log.e("UserBuy-Res", result);
		return result;
	}
	public static String getUserData() {
		String s = "";
		String lang = Locale.getDefault().getLanguage();
		if (!lang.equalsIgnoreCase("vi")) {
			lang = "en";
		}
		String requestUrl = API.GET_USER_DATA_URL + API.ACCESS_TOKEN + "="
				+ JsonUtil.getAccessToken(getAccesToken()) + "&" + API.LANG
				+ "=" + lang;
//		Log.e(TAG, requestUrl);
		HttpGet httpGet = new HttpGet(requestUrl);
		HttpClient client = HttpUtils.getNewHttpClient();
		HttpResponse response;
		try {
			response = client.execute(httpGet);
//			Log.e("daff", "connect " + response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				s = CommonUtils.inputStreamToString(inputStream);
//				Log.e(TAG, s);
				client.getConnectionManager().shutdown();
				client = null;
				return s;
			}
			client = null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		}
		return s;
	}
	public static String getGiftBoxList(String access_token) {
		String s = "";
		String lang = Locale.getDefault().getLanguage();
		if (!lang.equalsIgnoreCase("vi")) {
			lang = "en";
		}
		String requestUrl = API.GET_GIFT_BOX_LIST_URL + API.ACCESS_TOKEN + "="
				+ access_token + "&" + API.LANG
				+ "=" + lang;
//		Log.e(TAG, requestUrl);
		HttpGet httpGet = new HttpGet(requestUrl);
		HttpClient client = HttpUtils.getNewHttpClient();
		HttpResponse response;
		try {
			response = client.execute(httpGet);
//			Log.e("HttpHelperGetGiftBoxList", "connect " + response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				s = CommonUtils.inputStreamToString(inputStream);
				Log.e("HttpHelperGetGiftBoxList", s);
				client.getConnectionManager().shutdown();
				client = null;
				return s;
			}
			client = null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		}
		return s;
	}
	public static String openGiftBox(int giftbox_id,String game_token, 
			String bet, String access_token) {
		String lang = Locale.getDefault().getLanguage();
		if (!lang.equalsIgnoreCase("vi")) {
			lang = "en";
		}
		String result = "";
		String url_request = API.OPEN_GIFT_BOX_URL + "?" + API.ACCESS_TOKEN
				+ "=" + access_token + "&lang="+lang;
//		Log.e(TAG, url_request);
		HttpPost httpPost = new HttpPost(url_request);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
		ArrayList<NameValuePair> nameValuePairs = addGamePlayParameterForPost(
				game_token, bet);
		HttpClient client = HttpUtils.getNewHttpClient();
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = client.execute(httpPost);
//			Log.e("OpenGiftBox", response.getStatusLine().getStatusCode() + "");
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				result = CommonUtils.inputStreamToString(inputStream);
				client = null;
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		}
//		Log.e("OpenGiftBox", result);
		return result;
	}
	public static Boolean getBonusTym(String game_token, String access_token) {
		String lang = Locale.getDefault().getLanguage();
		if (!lang.equalsIgnoreCase("vi")) {
			lang = "en";
		}
		Boolean result = false;
		String url_request = API.RECEIVE_BONUS_TYM_URL  + API.ACCESS_TOKEN
				+ "=" + access_token + "&lang="+lang;
//		Log.e("getBonusTym", url_request);
		HttpPost httpPost = new HttpPost(url_request);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
		ArrayList<NameValuePair> arr = new ArrayList<NameValuePair>();
		arr.add(new BasicNameValuePair("game_token", game_token));
		arr.add(new BasicNameValuePair("client", "android"));
		HttpClient client = HttpUtils.getNewHttpClient();
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(arr));
			HttpResponse response = client.execute(httpPost);
			Log.e("getBonusTym", response.getStatusLine().getStatusCode() + "");
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				//result = CommonUtils.inputStreamToString(inputStream);
				client = null;
				result=true;
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		}
//		Log.e("getBonusTym - result : ", result.toString());
		return result;
	}
	public static String getAccesToken() {
		String result = "";
		String url_request = API.ACCESS_TOKEN_URL;
		HttpPost httpPost = new HttpPost(url_request);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
		ArrayList<NameValuePair> nameValuePairs = addParameter();
		HttpClient client = HttpUtils.getNewHttpClient();
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = client.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				result = CommonUtils.inputStreamToString(inputStream);
				client = null;
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		}
//		Log.e(TAG+"getAcessToken", result);
		return result;

	}

	public static ArrayList<NameValuePair> addParameter() {
		ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
		String requestToken = JsonUtil.getRequestToken(getRequestToken());
//		Log.e(TAG, requestToken);
		list.add(new BasicNameValuePair(API.REQUEST_TOKEN, requestToken));
		list.add(new BasicNameValuePair(API.CLIENT_ID, API.CLIENT_ID_VALUE));
		list.add(new BasicNameValuePair(API.CLIENT_SECRET,
				API.CLIENT_SECRET_VALUE));
		list.add(new BasicNameValuePair(API.REDIRECT_URI, API.REDIRECT_URI));
		list.add(new BasicNameValuePair(API.GRANT_TYPE, API.GRANT_TYPE_VALUE));
		list.add(new BasicNameValuePair(API.LANG, API.GRANT_TYPE_VALUE));
		return list;
	}

	public static String getRequestToken() {
		String result = "";
		String url_request = API.REQUEST_TOKEN_URI;
//		Log.e(TAG, url_request);
		HttpGet httpGet = new HttpGet(url_request);
		HttpClient client = HttpUtils.getNewHttpClient();
		HttpResponse response;
		try {
			response = client.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				result = CommonUtils.inputStreamToString(inputStream);
//				Log.e(TAG+"-response from getRequestToken", result);
				client.getConnectionManager().shutdown();
				client = null;
				return result;
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client.getConnectionManager().shutdown();
			client = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client.getConnectionManager().shutdown();
			client = null;
		}
//		Log.e(TAG, result);
		return result;
	}

	public static String loginUser(Context context, String username,
			String password,String access_token) {
		String result = "";
		if(access_token==null)
		{
			access_token=JsonUtil.getAccessToken(getAccesToken());
		}
		String lang = Locale.getDefault().getLanguage();
		if (!lang.equalsIgnoreCase("vi")) {
			lang = "en";
		}
		String url_request = API.LOGIN_URL + "?" + API.ACCESS_TOKEN + "="
				+ access_token + "&lang="+lang;
//		Log.e(TAG, url_request);
		HttpPost httpPost = new HttpPost(url_request);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
		ArrayList<NameValuePair> nameValuePairs = addLoginParameter(context,
				username, password);
		HttpClient client = HttpUtils.getNewHttpClient();
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = client.execute(httpPost);
//			Log.e(TAG+"-response from loginUser", response.getStatusLine().getStatusCode() + "");
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				result = CommonUtils.inputStreamToString(inputStream);
				client = null;
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		}
//		Log.e(TAG, result);
		return result;
	}

	public static String postGamePlay(String game_token, 
			String bet, String access_token) {
		String lang = Locale.getDefault().getLanguage();
		if (!lang.equalsIgnoreCase("vi")) {
			lang = "en";
		}
		String result = "";
		String url_request = API.GET_GAME_PLAY_URL + "?" + API.ACCESS_TOKEN
				+ "=" + access_token + "&lang="+lang;
//		Log.e(TAG, url_request);
		HttpPost httpPost = new HttpPost(url_request);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
		ArrayList<NameValuePair> nameValuePairs = addGamePlayParameterForPost(
				game_token, bet);
		HttpClient client = HttpUtils.getNewHttpClient();
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = client.execute(httpPost);
//			Log.e(TAG+"- response from postGamePlay", response.getStatusLine().getStatusCode() + "");
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				result = CommonUtils.inputStreamToString(inputStream);
				client = null;
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		}
//		Log.e(TAG, result);
		return result;
	}

	private static ArrayList<NameValuePair> addLoginParameter(Context context,
			String username, String password) {
		// TODO Auto-generated method stub
		ArrayList<NameValuePair> rs = new ArrayList<NameValuePair>();
		rs.add(new BasicNameValuePair(API.USER_NAME, username));
		rs.add(new BasicNameValuePair(API.PASSWORD, password));
		rs.add(new BasicNameValuePair(API.DEVICE_ID, CommonUtils
				.getDeviceId(context)));
		rs.add(new BasicNameValuePair(API.DEVICE_OS, CommonUtils.getDeviceOs()));
		rs.add(new BasicNameValuePair(API.DEVICE_OS_VERSION, CommonUtils
				.getDeviceVersion()));
		rs.add(new BasicNameValuePair(API.VENDOR, CommonUtils.getVendor()));
		rs.add(new BasicNameValuePair(API.PHONE_NUMBER, CommonUtils
				.getPhoneNumber(context)));
		rs.add(new BasicNameValuePair(API.CLIENT_VERSION, CommonUtils
				.getClientVersion(context) + ""));
		return rs;
	}

	public static String getUserData(String access_token) {
		// TODO Auto-generated method stub
		String s = "";
		String requestUrl = API.GET_USER_DATA_URL + API.ACCESS_TOKEN + "="
				+ access_token + "&" + API.LANG + "=" + API.LANG_VALUE;
//		Log.e(TAG, requestUrl);
		HttpPost httpPost = new HttpPost(requestUrl);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("version", String.valueOf(1)));
		HttpClient client = HttpUtils.getNewHttpClient();
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = client.execute(httpPost);
			Log.e("daff", "connect " + response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				s = CommonUtils.inputStreamToString(inputStream);
//				Log.e(TAG+"- getUserData", s);
				client.getConnectionManager().shutdown();
				client = null;
				return s;
			}
			client = null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		}
		return s;
	}

	private static ArrayList<NameValuePair> addGamePlayParameterForPost(
			String game_token, String bet) {
		ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("game_token", game_token));
		list.add(new BasicNameValuePair("bet", bet));
		list.add(new BasicNameValuePair("version", "1"));
		list.add(new BasicNameValuePair("client", "android"));
		return list;
	}
	public static String getTopUser(String accesstoken, int start, int limit) {
		String result="";
		String lang = Locale.getDefault().getLanguage();
		if (!lang.equalsIgnoreCase("vi")) {
			lang = "en";
		}
		String url_request = API.TOP_RANKING_URL + "access_token="
				+ accesstoken + "&lang=" + lang;
		HttpPost httpPost = new HttpPost(url_request);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("start",
				String.valueOf(start)));
		nameValuePairs.add(new BasicNameValuePair("limit",
				String.valueOf(limit)));
		nameValuePairs.add(new BasicNameValuePair("type",
				"yellow_tym"));
		HttpClient client = HttpUtils.getNewHttpClient();
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = client.execute(httpPost);
//			Log.e(TAG+"- response from getTopUser", response.getStatusLine().getStatusCode() + "");
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				result = CommonUtils.inputStreamToString(inputStream);
				client = null;
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		}
//		Log.e(TAG, result);
		return result;

	}
	public static String checkUserBirthday(String type,String access_token) {
		String lang = Locale.getDefault().getLanguage();
		if (!lang.equalsIgnoreCase("vi")) {
			lang = "en";
		}
		String result = "";
		String url_request = API.CHECK_BIRTHDAY_URL  + access_token + "&lang="+lang;
		HttpPost httpPost = new HttpPost(url_request);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("type" , type));
		nameValuePairs.add(new BasicNameValuePair("client", "android"));
		HttpClient client = HttpUtils.getNewHttpClient();
//		Log.e("type",type+"url:"+url_request);
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = client.execute(httpPost);
			Log.e("HttpHelper-CheckBirthday", response.getStatusLine().getStatusCode() + "");
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				result = CommonUtils.inputStreamToString(inputStream);
				client = null;
				inputStream.close();
				try {
					JSONObject jsonObject = new JSONObject(result);
					boolean status=jsonObject.getBoolean("status");
					if(status)
					{
						if(type.equals("check"))
						{
							int error_code=jsonObject.getInt("error_code");
							if(error_code==0)
							{
								JSONObject data=jsonObject.getJSONObject("data");
								int tym=data.getInt("tym");
								int received=data.getInt("received");
								if(received==1)
								{
									//already received the gift
									ConfirmUserBirthdayFailed event=new ConfirmUserBirthdayFailed();
									event.setStatus(true);
									EventBus.getDefault().post(event);
								}else
								{
									CheckUserBirthdaySucceed event=new CheckUserBirthdaySucceed();
									event.setNum_of_gold_tym(tym);
									EventBus.getDefault().post(event);
								}
								
							}else
							{
								ConfirmUserBirthdayFailed event=new ConfirmUserBirthdayFailed();
								event.setStatus(false);
								EventBus.getDefault().post(event);
							}
							
						}else
						{
							
							EventBus.getDefault().post(new ConfirmUserBirthdaySucceed());
						}
					}else if(!status)
					{
						if(type.equals("check"))
						{
							CheckUserBirthdayFailed event=new CheckUserBirthdayFailed();
							EventBus.getDefault().post(event);
						}else
						{
							ConfirmUserBirthdayFailed event=new ConfirmUserBirthdayFailed();
							event.setStatus(false);
							EventBus.getDefault().post(event);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
					return null;
				}
				
				
			}else
			{
				EventBus.getDefault().post(new CheckUserBirthdayFailed());
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			client = null;
		}
//		Log.e("checkUserBirthday", result);
		return result;
	}
	
	public static void loginUser(String accessToken,String username,String password) {
		String lang = Locale.getDefault().getLanguage();
		if (!lang.equalsIgnoreCase("vi")) {
			lang = "en";
		}
		String url_request = Constants.LOGIN_ENDPOINT+accessToken+ "&lang=" +lang;
		HttpPost httpPost = new HttpPost(url_request);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
		ArrayList<NameValuePair> rs = new ArrayList<NameValuePair>();
		rs.add(new BasicNameValuePair(API.USER_NAME, username));
		rs.add(new BasicNameValuePair(API.PASSWORD, password));
		HttpClient client = HttpUtils.getNewHttpClient();
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(rs));
			HttpResponse response = client.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				String result = inputStreamToString(inputStream);
				Log.e("login res","login res:"+result);
				client = null;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			client = null;
		} catch (ClientProtocolException e) {
			e.printStackTrace();client = null;
		} catch (IOException e) {
			e.printStackTrace();client = null;
		}
	}
	
	public static String getTopContent(String type, int cateId, String accessToken, int storeId, int start,String version,String isTablet) {
		String res="";
		String endpoint = "";
		if(accessToken.equals("")){
			accessToken="03cea4ee604e07b241c4c097feae3274";
		}
//		String version = "android_" + getAppVersion(context);
//		countryCode = Utils.getStaticCountryCode(context);
		if (type.equalsIgnoreCase("Newest")) {
			endpoint = Constants.TOPNEW_ENDPOINT + accessToken;
		} else if (type.equalsIgnoreCase("Top Download")) {
			endpoint = Constants.TOPDOWNLOAD_ENDPOINT + accessToken;
		} else if (type.equalsIgnoreCase("Top Paid")) {
			endpoint = Constants.TOPPAID_ENDPOINT + accessToken;
		} else if (type.equalsIgnoreCase("Top Free")) {
			endpoint = Constants.TOPFREE_ENDPOINT + accessToken;
		} else if (type.equalsIgnoreCase("Hot")) {
			endpoint = Constants.HOT_ENDPOINT + accessToken;
		}
		HttpPost httpPost = new HttpPost(endpoint);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
		ArrayList<NameValuePair> rs = new ArrayList<NameValuePair>();
		rs.add(new BasicNameValuePair("store_id", String.valueOf(storeId)));
		if (cateId != 0) {
			rs.add(new BasicNameValuePair("category_id",  String.valueOf(cateId)));
		}
		String input = cateId + "appstorevn_app" + isTablet + "20" + start + storeId + version + "AppStoreVnAndroidNative!@#";
		String hash = Utils.generateHashMD5(input);
		rs.add(new BasicNameValuePair("start",  String.valueOf(start)));
		rs.add(new BasicNameValuePair("client", "appstorevn_app"));
		rs.add(new BasicNameValuePair("filter",  isTablet));
		rs.add(new BasicNameValuePair("limit",  "20"));
		rs.add(new BasicNameValuePair("hash",  hash));
		rs.add(new BasicNameValuePair("v",  version));
		HttpClient client = HttpUtils.getNewHttpClient();
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(rs));
			HttpResponse response = client.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				res = inputStreamToString(inputStream);
				Log.e("getTop","getTop:"+res);
				client = null;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			client = null;
		} catch (ClientProtocolException e) {
			e.printStackTrace();client = null;
		} catch (IOException e) {
			e.printStackTrace();client = null;
		}
		return res;
	}
	
	public static void loginFBUser(String accessToken,String fbemail,String fbaccessToken) {
		String lang = Locale.getDefault().getLanguage();
		if (!lang.equalsIgnoreCase("vi")) {
			lang = "en";
		}
		String url_request = Constants.FB_LOGIN_ENDPOINT+accessToken+"&lang=" +lang;
		HttpPost httpPost = new HttpPost(url_request);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
		ArrayList<NameValuePair> rs = new ArrayList<NameValuePair>();
		rs.add(new BasicNameValuePair("facebook_access_token", fbaccessToken));
		rs.add(new BasicNameValuePair("facebook_email", fbemail));
		HttpClient client = HttpUtils.getNewHttpClient();
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(rs));
			HttpResponse response = client.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream inputStream = response.getEntity().getContent();
				String result = inputStreamToString(inputStream);
				Log.e("login res","login fb res:"+result);
				client = null;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			client = null;
		} catch (ClientProtocolException e) {
			e.printStackTrace();client = null;
		} catch (IOException e) {
			e.printStackTrace();client = null;
		}
	}
	
	public static String inputStreamToString(InputStream is) {
		String line = "";
		StringBuilder total = new StringBuilder();
		// Wrap a BufferedReader around the InputStream
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		// Read response until the end
		try {
			while ((line = rd.readLine()) != null) {
				total.append(line);
			}
		} catch (IOException e) {
			Log.e(TAG, "Error read data");
			return null;
		}
		// Return full string
		return total.toString();
	}
}
